package com.example.lifecycleserviceusage

import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 感知生命周期service
 */
class MyLifecycleService : LifecycleService() {
    private var number = 0

    //    private
    var numberLiveData = MutableLiveData(0)
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        lifecycleScope.launch {
            while (true) {
                delay(1000)
                Log.d("TAG", "onstartcommand: ${number++}")
            }
        }

        return super.onStartCommand(intent, flags, startId)
    }

    override fun onCreate() {
        super.onCreate()
    }

    override fun onBind(intent: Intent): IBinder? {
        super.onBind(intent)
        lifecycleScope.launch {
            while (true) {
                delay(1000)
                numberLiveData.value = numberLiveData.value?.plus(1)
                Log.d("TAG", "livedata: ${numberLiveData.value}")
                // 耗时任务，定时任务这里
            }
        }
        return MyBinder()
    }

    inner class MyBinder : Binder() {
        // 传递本身类MyLifecycleService对象
        val service = this@MyLifecycleService
    }
}